/**
 * @file YzhResourceManagement.vue
 * @description 基于yzh_resource表的资源管理页面
 * @created 2024-07-14
 */

<template>
  <div class="resource-management">
    <div class="page-header">
      <h2>教学资源管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="openUploadDialog">
          <el-icon><Upload /></el-icon>上传资源
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区 -->
    <div class="search-filter-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="资源名称">
          <el-input v-model="searchForm.name" placeholder="请输入资源名称" clearable />
        </el-form-item>
        <el-form-item label="资源类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option v-for="type in resourceTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 资源列表表格 -->
    <el-card class="resource-table-container">
      <el-table
        v-loading="loading"
        :data="resourceList"
        border
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="name" label="资源名称" min-width="150">
          <template #default="scope">
            <el-tooltip :content="scope.row.description || '无描述'" placement="top" :show-after="500">
              <span class="resource-name">{{ scope.row.name }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category_name" label="分类" width="120" />
        <el-table-column prop="size" label="大小" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="download_count" label="下载次数" width="100" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" sortable />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" link @click="handlePreview(scope.row)">
              <el-icon><View /></el-icon>预览
            </el-button>
            <el-button type="primary" link @click="handleDownload(scope.row)">
              <el-icon><Download /></el-icon>下载
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上传资源对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传资源"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="uploadForm.name" placeholder="请输入资源名称" />
          <div class="form-item-tip">资源名称将显示在资源列表中</div>
        </el-form-item>
        
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="uploadRef"
            class="resource-uploader"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持各类文档、图片、视频、音频等格式文件，单个文件不超过100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="资源分类" prop="category_id">
          <el-select v-model="uploadForm.category_id" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
          <div class="form-item-tip">默认为"教学课件"</div>
        </el-form-item>
        
        <el-form-item label="资源类型" prop="type">
          <el-select v-model="uploadForm.type" placeholder="请选择类型">
            <el-option v-for="type in resourceTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
          <div class="form-item-tip">默认为"document"</div>
        </el-form-item>
        
        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述（可选）"
          />
          <div class="form-item-tip">若不填写，将自动生成描述</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploadLoading">上传</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑资源对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑资源信息"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入资源名称" />
        </el-form-item>
        <el-form-item label="资源分类" prop="category_id">
          <el-select v-model="editForm.category_id" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择类型">
            <el-option v-for="type in resourceTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="editLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 资源预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="资源预览"
      width="800px"
    >
      <div class="resource-preview" v-if="currentResource">
        <div class="resource-info">
          <h3>{{ currentResource.name }}</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="ID">{{ currentResource.id }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ getTypeLabel(currentResource.type) }}</el-descriptions-item>
            <el-descriptions-item label="大小">{{ formatFileSize(currentResource.size) }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentResource.create_time }}</el-descriptions-item>
            <el-descriptions-item label="下载次数">{{ currentResource.download_count }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(currentResource.status)">
                {{ getStatusText(currentResource.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">
              {{ currentResource.description || '无描述' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="preview-actions">
          <el-button type="primary" @click="handleDownload(currentResource)">
            <el-icon><Download /></el-icon>下载资源
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Download, View, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { yzhResourceAPI } from '@/api/admin/yzh_resource'

// 资源列表数据
const resourceList = ref([])
const loading = ref(false)
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 分类列表
const categories = ref([
  { id: 1, name: '教学课件' },
  { id: 2, name: '试题资源' },
  { id: 3, name: '视频资源' },
  { id: 4, name: '图片资源' },
  { id: 5, name: '音频资源' },
  { id: 6, name: '文档资源' },
])

// 资源类型选项
const resourceTypes = [
  { value: 'document', label: '文档' },
  { value: 'ppt', label: 'PPT课件' },
  { value: 'pdf', label: 'PDF' },
  { value: 'video', label: '视频' },
  { value: 'audio', label: '音频' },
  { value: 'image', label: '图片' },
  { value: 'code', label: '代码' },
  { value: 'other', label: '其他' }
]

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  categoryId: null,
  sortBy: '',
  sortOrder: ''
})

// 上传对话框相关
const uploadDialogVisible = ref(false)
const uploadFormRef = ref(null)
const uploadRef = ref(null)
const uploadLoading = ref(false)
const uploadForm = reactive({
  name: '',
  category_id: 1, // 默认分类ID为1
  type: 'document', // 默认类型为document
  description: '',
  file: null
})

// 表单验证规则
const uploadRules = {
  name: [
    { required: true, message: '请输入资源名称', trigger: 'blur' },
    { max: 100, message: '资源名称不能超过100个字符', trigger: 'blur' }
  ],
  category_id: [
    { required: false, message: '请选择资源分类', trigger: 'change' }
  ],
  type: [
    { required: false, message: '请选择资源类型', trigger: 'change' }
  ],
  description: [
    { required: false },
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ]
}

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editLoading = ref(false)
const editForm = reactive({
  id: null,
  name: '',
  category_id: null,
  type: '',
  description: ''
})

// 预览对话框相关
const previewDialogVisible = ref(false)
const currentResource = ref(null)

// 初始化数据
onMounted(() => {
  fetchResourceList()
  fetchCategories()
})

// 获取资源列表
const fetchResourceList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      name: searchForm.name || undefined,
      type: searchForm.type || undefined,
      category_id: searchForm.categoryId || undefined,
      sort_by: searchForm.sortBy || undefined,
      sort_order: searchForm.sortOrder || undefined
    }
    
    // 调用API获取数据
    const res = await yzhResourceAPI.getResourceList(params)
    
    if (res && res.status === 'success' && res.data) {
      resourceList.value = res.data.items || res.data
      pagination.total = res.data.total || res.data.length
      console.log('加载资源列表成功:', resourceList.value)
    } else {
      // API返回失败，使用模拟数据
      console.warn('API返回数据格式不正确，使用模拟数据')
      const mockData = generateMockData()
      resourceList.value = mockData.items
      pagination.total = mockData.total
    }
  } catch (error) {
    console.error('获取资源列表失败:', error)
    ElMessage.error('获取资源列表失败，使用模拟数据')
    
    // 出错时使用模拟数据
    const mockData = generateMockData()
    resourceList.value = mockData.items
    pagination.total = mockData.total
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    // 调用API获取分类
    const res = await yzhResourceAPI.getResourceCategories()
    
    if (res && res.status === 'success' && res.data) {
      categories.value = res.data
      console.log('获取分类列表成功:', categories.value)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 刷新数据
const refreshData = () => {
  fetchResourceList()
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchResourceList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'sortBy' || key === 'sortOrder' ? '' : null
  })
  pagination.currentPage = 1
  fetchResourceList()
}

// 排序变化处理
const handleSortChange = ({ prop, order }) => {
  if (prop && order) {
    searchForm.sortBy = prop
    searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
  } else {
    searchForm.sortBy = ''
    searchForm.sortOrder = ''
  }
  fetchResourceList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchResourceList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchResourceList()
}

// 打开上传对话框
const openUploadDialog = () => {
  uploadForm.name = ''
  uploadForm.category_id = 1 // 默认分类ID为1
  uploadForm.type = 'document' // 默认类型为document
  uploadForm.description = ''
  uploadForm.file = null
  
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  
  uploadDialogVisible.value = true
}

// 文件变化处理
const handleFileChange = (file) => {
  uploadForm.file = file.raw
  // 如果未设置资源名称，使用文件名
  if (!uploadForm.name && file.name) {
    uploadForm.name = file.name.split('.')[0] || file.name
  }
  
  // 根据文件扩展名设置资源类型
  const ext = file.name.split('.').pop().toLowerCase()
  if (ext) {
    if (['doc', 'docx', 'txt'].includes(ext)) {
      uploadForm.type = 'document'
    } else if (['ppt', 'pptx'].includes(ext)) {
      uploadForm.type = 'ppt'
    } else if (ext === 'pdf') {
      uploadForm.type = 'pdf'
    } else if (['mp4', 'avi', 'mov', 'wmv'].includes(ext)) {
      uploadForm.type = 'video'
    } else if (['mp3', 'wav', 'ogg'].includes(ext)) {
      uploadForm.type = 'audio'
    } else if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext)) {
      uploadForm.type = 'image'
    } else if (['py', 'js', 'java', 'c', 'cpp', 'cs', 'html', 'css', 'php'].includes(ext)) {
      uploadForm.type = 'code'
    }
  }
}

// 文件移除处理
const handleFileRemove = () => {
  uploadForm.file = null
}

// 取消上传
const cancelUpload = () => {
  uploadDialogVisible.value = false
}

// 提交上传
const submitUpload = async () => {
  if (!uploadForm.file) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  uploadFormRef.value.validate(async (valid) => {
    if (valid) {
      uploadLoading.value = true
      try {
        // 创建FormData对象，用于文件上传
        const formData = new FormData()
        formData.append('file', uploadForm.file)
        formData.append('name', uploadForm.name)
        formData.append('category_id', uploadForm.category_id || 1) // 默认分类ID为1
        formData.append('type', uploadForm.type || 'document') // 默认类型为document
        
        if (uploadForm.description) {
          formData.append('description', uploadForm.description)
        }
        
        console.log('上传资源数据:', Object.fromEntries(formData))
        
        // 调用API上传文件
        const res = await yzhResourceAPI.uploadResourceFile(formData)
        
        console.log('上传响应:', res)
        
        if (res && (res.status === 'success' || res.code === 200)) {
          ElMessage.success(res.message || '资源上传成功')
          uploadDialogVisible.value = false
          fetchResourceList() // 刷新列表
        } else {
          throw new Error(res.message || '上传失败')
        }
      } catch (error) {
        console.error('上传资源失败:', error)
        ElMessage.error('上传资源失败：' + (error.message || '未知错误'))
      } finally {
        uploadLoading.value = false
      }
    }
  })
}

// 预览资源
const handlePreview = (row) => {
  currentResource.value = row
  previewDialogVisible.value = true
}

// 下载资源
const handleDownload = (row) => {
  try {
    // 获取下载链接
    const downloadUrl = yzhResourceAPI.getDownloadUrl(row.id)
    
    // 创建一个隐藏的<a>元素用于下载
    const link = document.createElement('a')
    link.href = downloadUrl
    link.target = '_blank'
    link.download = row.name // 设置下载文件名
    
    // 模拟点击
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success(`开始下载资源：${row.name}`)
  } catch (error) {
    console.error('下载资源失败:', error)
    ElMessage.error('下载资源失败，请重试')
  }
}

// 编辑资源
const handleEdit = (row) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.category_id = row.category_id
  editForm.type = row.type
  editForm.description = row.description || ''
  
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        const data = {
          name: editForm.name,
          category_id: editForm.category_id,
          type: editForm.type,
          description: editForm.description
        }
        
        // 调用API更新资源
        const res = await yzhResourceAPI.updateResource(editForm.id, data)
        
        if (res && res.status === 'success') {
          ElMessage.success('资源信息更新成功')
          editDialogVisible.value = false
          fetchResourceList() // 刷新列表
        } else {
          throw new Error(res.message || '更新失败')
        }
      } catch (error) {
        console.error('更新资源失败:', error)
        ElMessage.error('更新资源失败：' + (error.message || '未知错误'))
      } finally {
        editLoading.value = false
      }
    }
  })
}

// 删除资源
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除资源 "${row.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用API删除资源
      const res = await yzhResourceAPI.deleteResource(row.id)
      
      if (res && res.status === 'success') {
        ElMessage.success('资源删除成功')
        fetchResourceList() // 刷新列表
      } else {
        throw new Error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除资源失败:', error)
      ElMessage.error('删除资源失败：' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  let value = parseInt(size, 10) || 0
  while (value >= 1024 && index < units.length - 1) {
    value /= 1024
    index++
  }
  return `${value.toFixed(2)} ${units[index]}`
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusNum = parseInt(status, 10)
  const map = {
    0: 'info',    // 待审核
    1: 'success', // 审核通过
    2: 'danger',  // 审核驳回
    3: 'warning'  // 已下架
  }
  return map[statusNum] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusNum = parseInt(status, 10)
  const map = {
    0: '待审核',
    1: '已发布',
    2: '已驳回',
    3: '已下架'
  }
  return map[statusNum] || '未知状态'
}

// 获取资源类型标签样式
const getTypeTagType = (type) => {
  const map = {
    'document': 'success',
    'ppt': '',
    'pdf': 'danger',
    'video': 'warning',
    'audio': 'info',
    'image': 'success',
    'code': 'warning',
    'other': 'info'
  }
  return map[type] || ''
}

// 获取资源类型标签文本
const getTypeLabel = (type) => {
  const found = resourceTypes.find(item => item.value === type)
  return found ? found.label : type
}

// 生成模拟数据方法 (实际项目中删除此方法)
const generateMockData = () => {
  // 固定资源列表，包含用户提供的两条记录
  const fixedItems = [
    {
      id: 5,
      name: "ai_teach教师表20250410023149.docx",
      category_id: 1,
      category_name: '教学课件',
      type: "document",
      path: "H:\\毕业设计\\ai_teach\\..\\resource_files\\ai_teach教师表20250410023149.docx",
      size: 11139,
      description: "通过API上传的document类型资源",
      status: 0,
      audit_opinion: null,
      download_count: 0,
      create_time: "2025-05-10 21:15:56",
      update_time: "2025-05-10 21:15:56",
      creator_id: 0
    },
    {
      id: 8,
      name: "《基于生成式人工智能的教学管理平台的分析设计——管理端子系统》初稿.pdf",
      category_id: 1,
      category_name: '教学课件',
      type: "document",
      path: "H:\\毕业设计\\ai_teach\\..\\resource_files\\《基于生成式人工智能的教学管理平台的分析设计——管理端子系统》初稿.pdf",
      size: 2923379,
      description: "通过API上传的document类型资源",
      status: 0,
      audit_opinion: null,
      download_count: 0,
      create_time: "2025-05-10 21:54:01",
      update_time: "2025-05-10 21:54:01",
      creator_id: 0
    }
  ];
  
  return {
    items: fixedItems,
    total: fixedItems.length
  };
}
</script>

<style scoped>
.resource-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.resource-table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.resource-name {
  cursor: pointer;
  color: #409eff;
}

.resource-uploader {
  width: 100%;
}

.resource-preview {
  padding: 20px;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-item-tip {
  font-size: 0.8em;
  color: #909399;
  margin-top: 5px;
}
</style> 